﻿using PSL.Lexer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSL.ST
{
    /// <summary>
    /// Class to splitt the syntaxtree in different parts
    /// </summary>
    public class SyntaxTreeParser
    {
        #region Private Member
        private SyntaxTree syntaxTree;
        #endregion

        #region Constructor
        /// <summary>
        /// Create PSL-Runtime
        /// </summary>
        /// <param name="InitialSyntaxTree"></param>
        public SyntaxTreeParser(SyntaxTree InitialSyntaxTree)
        {
            syntaxTree = InitialSyntaxTree;
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// Get Function-Declerations
        /// </summary>
        /// <returns>Syntax-Tree with only function-delcarations</returns>
        public SyntaxTree GetFunctionDeclarations()
        {
            SyntaxTree returnValue = new SyntaxTree();
            IList<TreeNode> toRemove = new List<TreeNode>();

            // Get all SyntaxTreeNodes
            foreach (DeclareFunctionNode node in syntaxTree.RootNode.FindChildrenOfType<DeclareFunctionNode>())
            {
                node.ParentNode = returnValue.RootNode;
                returnValue.RootNode.Children.Add(node);

                toRemove.Add(node);
            }

            // Remove from old tree
            foreach (TreeNode node in toRemove)
            {
                syntaxTree.RootNode.Children.Remove(node);
            }

            return returnValue;
        }

        /// <summary>
        /// Get Syntaxtree with the code which should be executed direct
        /// </summary>
        /// <returns>Instance of an syntax-tree</returns>
        public SyntaxTree GetSyntaxTreeToExecute()
        {
            SyntaxTree returnValue = new SyntaxTree();
            IList<TreeNode> toRemove = new List<TreeNode>();

            // Get all SyntaxTreeNodes
            foreach (TreeNode node in syntaxTree.RootNode.FindChildrenBesidesOfType<DeclareFunctionNode>())
            {
                node.ParentNode = returnValue.RootNode;
                returnValue.RootNode.Children.Add(node);

                toRemove.Add(node);
            }

            // Remove from old tree
            foreach (TreeNode node in toRemove)
            {
                syntaxTree.RootNode.Children.Remove(node);
            }

            return returnValue;
        }
        #endregion
    }
}
